package com.ruoyi.common.utils;

import com.github.jaiimageio.impl.plugins.tiff.TIFFImageMetadata;
import com.github.jaiimageio.impl.plugins.tiff.TIFFImageWriter;
import com.github.jaiimageio.plugins.tiff.*;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Iterator;

public class TiffUtil {

    public static void main(String[] args) throws Exception {
//        URL urlfile = new URL("https://rh-images.xiaoyaoyou.com/01acb4e9d67072c0f9973be7ad23b74f/output/ComfyUI_00015_exydr_1746263932.png");
        URL urlfile = new URL("https://rh-images.xiaoyaoyou.com/01acb4e9d67072c0f9973be7ad23b74f/output/ComfyUI_00137_ccbta_1746868324.png");
        InputStream inStream = urlfile.openStream();
        BufferedImage bimg = ImageIO.read(inStream);
        File f = writeImage(bimg, "E:\\imageio-test-1.tiff");
    }

    public static File writeImage(BufferedImage image, String filePath) throws Exception {
        TIFFImageWriter tiffImageWriter = getImageWriter();
        TIFFImageWriteParam writeParams = (TIFFImageWriteParam) tiffImageWriter.getDefaultWriteParam();

        // 获取并配置元数据
        IIOMetadata metadata = tiffImageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(image), writeParams);
        if (metadata instanceof TIFFImageMetadata) {
            TIFFImageMetadata tiffMetadata = (TIFFImageMetadata) metadata;
            TIFFDirectory dir = tiffMetadata.getRootIFD();

            // 获取 TIFFTag 对象
            TIFFTag xResTag = BaselineTIFFTagSet.getInstance().getTag(BaselineTIFFTagSet.TAG_X_RESOLUTION);
            TIFFTag yResTag = BaselineTIFFTagSet.getInstance().getTag(BaselineTIFFTagSet.TAG_Y_RESOLUTION);
            TIFFTag resUnitTag = BaselineTIFFTagSet.getInstance().getTag(BaselineTIFFTagSet.TAG_RESOLUTION_UNIT);

            // 设置 XResolution（300 DPI）
            dir.addTIFFField(new TIFFField(
                    xResTag, // 直接获取预定义标签对象
                    5,  // RATIONAL 类型码
                    1,
                    new long[][]{{300, 1}}  // 使用 long[][] 表示 RATIONAL
//                    new long[][]{{1, 1}}  // 使用 long[][] 表示 RATIONAL
            ));

            // 设置 YResolution（300 DPI）
            dir.addTIFFField(new TIFFField(
                    yResTag,
                    5,
                    1,
                    new long[][]{{300, 1}}
//                    new long[][]{{1, 1}}  // 使用 long[][] 表示 RATIONAL

            ));

            // 设置 ResolutionUnit 为英寸（使用 char 数组）
            dir.addTIFFField(new TIFFField(
                    resUnitTag,
                    3,  // SHORT 类型码
                    1,
                    new char[]{(char) BaselineTIFFTagSet.RESOLUTION_UNIT_INCH}  // 转换为 char 数组
            ));
        }

        createFile(new File(filePath));
        File f = new File(filePath);
        try (ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(new FileOutputStream(f))) {
            tiffImageWriter.setOutput(imageOutputStream);
            IIOImage iioImage = new IIOImage(image, null, metadata);
            tiffImageWriter.write(null, iioImage, writeParams);
        }
        tiffImageWriter.dispose();
        return f;
    }

    private static TIFFImageWriter getImageWriter() {
        Iterator<ImageWriter> writers = ImageIO.getImageWritersBySuffix("tiff");
        while (writers.hasNext()) {
            ImageWriter writer = writers.next();
            if (writer instanceof TIFFImageWriter) {
                return (TIFFImageWriter) writer;
            }
        }
        throw new IllegalStateException("No TIFF image writer found");
    }

    public static void createFile(File file) throws IOException {
        if (!file.exists()) {
            File parentDir = file.getParentFile();
            if (parentDir != null && !parentDir.exists()) {
                parentDir.mkdirs();
            }
            file.createNewFile();
        }
    }
}